package org.net5ijy.security.util;

import javax.servlet.http.HttpServletRequest;

/**
 * 一些请求头key
 *
 * @author 创建人：xuguofeng
 * @version 创建于：2018年9月17日 下午2:00:39
 */
public class RequestUtil {

  /**
   * X-Requested-With请求头的key
   */
  public static final String X_REQUESTED_WITH_HEADER = "X-Requested-With";

  /**
   * XMLHttpRequest
   */
  public static final String XML_HTTP_REQUEST = "XMLHttpRequest";

  /**
   * 获取contextPath之后的请求uri<br /> <br />
   *
   * 比如请求是http://localhost:8080/test/index.html<br /> <br />
   *
   * 获取到的就是/index.html<br />
   *
   * @author 创建人：xuguofeng
   */
  public static String getRequestUri(HttpServletRequest request) {
    String path = request.getContextPath();
    String uri = request.getRequestURI();
    uri = uri.replace(path, "");
    return uri;
  }

  /**
   * 获取从contextPath开始的URL<br /> <br />
   *
   * 比如项目是/test，参数relativeUrl是/index.html<br /> <br />
   *
   * 返回的就是/test/index.html<br />
   *
   * @author 创建人：xuguofeng
   */
  public static String getRedirectUrl(HttpServletRequest request,
      String relativeUrl) {
    String path = request.getContextPath();
    return path + relativeUrl;
  }

  /**
   * 判断请求是否是AJAX<br />
   *
   * @author 创建人：xuguofeng
   */
  public static boolean isAjax(HttpServletRequest request) {
    // 获取X-Requested-With请求头
    String xmlHttpRequest = request.getHeader(X_REQUESTED_WITH_HEADER);
    return RequestUtil.XML_HTTP_REQUEST.equals(xmlHttpRequest);
  }
}
